//
//  SMCardListViewController.m
//  SaiMer
//
//  Created by MacBook on 2019/5/25.
//  Copyright © 2019 stoneobs.qq.com. All rights reserved.
//

#import "THMineCollectViewController.h"

#import "THMineCollectionTableViewCell.h"

@interface THMineCollectViewController ()<UIScrollViewDelegate>
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**< <##> */

@property(nonatomic, strong) STButton                     *editButton;/**<  */
@property(nonatomic, strong) UIView                     *bootomView;/**<  */
@property(nonatomic, strong) STButton                     *allButton;/**<  */
@end

@implementation THMineCollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weakSelf =  self;
    self.title = @"我的收藏";
    
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                              title:@"删除"
                                                         titleColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                          titleFont:15
                                                       cornerRadius:0
                                                    backgroundColor:nil
                                                    backgroundImage:nil
                                                              image:nil];
    
//    [self stoneobs_fun_st_setRightItemWithView:stoneobs_ui_button];
    self.editButton = stoneobs_ui_button;
    [stoneobs_ui_button setTitle:@"完成" forState:UIControlStateSelected];
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {

        [weakSelf stoneobs_fun_st_rightBarAction:nil];
        
    }];
    
    
    self.tableView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf stoneobs_send_list_request];
    }];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    // Do any additional setup after loading the view.
}

- (void)configBootomView{
    __weak typeof(self) weakSelf =  self;
    [self.bootomView removeFromSuperview];
    UIView * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, STONEOBS_UI_UISCREEN_HEIGHT, UISCREEN_WIDTH, 49 + 30)];
    [self.view addSubview:bootomView];
    bootomView.backgroundColor = UIColor.whiteColor;
    [bootomView stoneobs_fun_st_showBottomLine];
    self.bootomView = bootomView;
    ({
        UIImage * image = [ST_IMAGE_NAMED(@"wxzzf") imageScaledToSize:CGSizeMake(22, 22)];
        UIImage * simage = [ST_IMAGE_NAMED(@"xzzhifu") imageScaledToSize:CGSizeMake(22, 22)];
        self.allButton = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 100, 49)
                                                   title:@"全选"
                                              titleColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                               titleFont:15
                                            cornerRadius:0
                                         backgroundColor:nil
                                         backgroundImage:nil
                                                   image:image];
        [self.allButton setImage:simage forState:UIControlStateSelected];
        [self.bootomView addSubview:self.allButton];
        [self.allButton setClicAction:^(UIButton *sender) {
            [weakSelf onSelctedAllChosedButton];
        }];
        self.allButton.left = 15;
        self.allButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
        
        
        STButton* cancelBut= [[STButton alloc] initWithFrame:CGRectMake(0, 0, 71, 27)
                                                       title:@"删除"
                                                  titleColor:UIColor.whiteColor
                                                   titleFont:15
                                                cornerRadius:4
                                             backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                             backgroundImage:nil
                                                       image:nil];
        cancelBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [cancelBut setClicAction:^(UIButton *sender) {
            [weakSelf onSelctedDeleteButton];
        }];
        cancelBut.centerY = self.allButton.centerY;
        cancelBut.right = UISCREEN_WIDTH - 15;
        [self.bootomView addSubview:cancelBut];
        
    });
    
    
    [UIView animateWithDuration:0.25 animations:^{
        self.bootomView.top = TMUtils.stoneobs_fun_get_tabBarTop;
    }];
}


#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return THMineCollectionTableViewCell.stoneobs_ui_cell_height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    THMineCollectionTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[THMineCollectionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    THGoodModel * model = self.dataSouce[indexPath.row];
    cell.model =model;
    __weak typeof(self) weakSelf =  self;
    [cell.deleteButton setClicAction:^(UIButton *sender) {
        [THHomeDataController stoneobs_fun_collect_good:model.g_id handle:^(NSError *error, BOOL success, NSDictionary *resp) {
           
            [weakSelf.dataSouce removeObject:model];
            [weakSelf.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationLeft];
            [weakSelf.tableView reloadData];
            
        }];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    THGoodModel * model = self.dataSouce[indexPath.row];
    [TMUtils goto_good_detail_witdh_id:model.goods_id];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
//    if (!self.tableView.isEditing) {
//        THGoodModel * model = self.dataSouce[indexPath.row];
//    }else{
//        model.isSlected = !model.isSlected ;
//        
//    }
}
- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    self.editButton.selected = !self.editButton.selected;
    [self.tableView setEditing:self.editButton.selected animated:YES];
    if (self.editButton.selected) {
        [self configBootomView];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.bootomView.top = STONEOBS_UI_UISCREEN_HEIGHT;
        }];
    }
    
}
- (void)onSelctedAllChosedButton{
    self.allButton.selected = !self.allButton.selected;
    if (self.allButton.selected) {
        for (NSInteger i = 0; i < self.dataSouce.count; i ++ ) {
            THGoodModel * model = self.dataSouce[i];
            model.isSlected = YES;
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }else{
        for (NSInteger i = 0; i < self.dataSouce.count; i ++ ) {
             THGoodModel * model = self.dataSouce[i];
             model.isSlected = NO;
             [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
         }
    }
}
- (void)onSelctedDeleteButton{
    
}
#pragma mark --BeautyFood_net netWork Method
- (void)configRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf stoneobs_send_list_request];
    }];
}
- (void)stoneobs_send_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
       NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
       NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
       if (stoneobs_net_user_id.length) {
           [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
       }
       if (stoneobs_net_user_token.length) {
           [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
       }
       [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
       NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/goods/collections"];
       DDLogInfo(@"url:%@",stoneobs_net_net_url);
       DDLogInfo(@"param:%@",stoneobs_net_param_dic);
       [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                    method:STHttpRequestType_stoneobs_enumGet
                                                                parameters:stoneobs_net_param_dic
                                                                   success:^(NSURLSessionDataTask *operation, id responseObject) {
           [SVProgressHUD dismiss];
           NSDictionary * dic = [responseObject valueForKey:@"data"];
           NSArray * array = dic[@"items"];
           NSArray * objArray = [THGoodModel mj_objectArrayWithKeyValuesArray:array];
           NSInteger total = [dic[@"total"] integerValue];//总数量;
           CGFloat perPage = [dic[@"perPage"] floatValue];
           CGFloat allpage = total / perPage;
           if (self.page == 1) {
               self.dataSouce = objArray.mutableCopy;
               [self.tableView reloadData];
               if (allpage>1) {
                   [self configRefreshFooter];
               }
               [self.tableView.mj_header endRefreshing];
           }else{
               if (self.page < allpage) {
                   [self.tableView.mj_footer endRefreshing];
               }else{
                   [self.tableView.mj_footer endRefreshingWithNoMoreData];
               }
               [self.dataSouce addObjectsFromArray:objArray];
               [self.tableView reloadData];
           }
           // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
           DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
           
           
       } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
           [SVProgressHUD dismiss];
           DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                      stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
       }];
}

@end

